<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 2017/1/10
 * Time: 下午1:59
 */

namespace Home\Controller;


use Common\Controller\HomeController;
use Common\Model\GoodsAttrModel;
use Common\Model\GoodsListModel;
use Common\Model\GoodsModel;
use Common\Model\TypeAttrModel;

class GoodsController extends HomeController
{
	protected $gid;
	protected $tid;
	protected $prefix;//表前缀
	protected $goodsModel;


	public function __init ()
	{
		$this->gid        = I( 'get.gid' );
		$this->tid        = I( 'get.tid' );
		$this->goodsModel = new GoodsModel();
		$this->prefix     = C( 'DB_PREFIX' );
	}

	public function detail ()
	{

		$goods             = $this->goodsModel->join( "__GOODS_DETAIL__ on __GOODS__.gid=__GOODS_DETAIL__.gid" )->where( "{$this->prefix}goods.gid={$this->gid}" )->find();
		$goods[ 'small' ]  = explode( ',' , $goods[ 'small' ] );
		$goods[ 'medium' ] = explode( ',' , $goods[ 'medium' ] );
		$goods[ 'big' ]    = explode( ',' , $goods[ 'big' ] );
		$this->assign( 'goods' , $goods );


		//获取规格属性的数据
		$specList = ( new TypeAttrModel() )->getSpecList( $this->tid , $this->gid );
		$this->assign( 'specList' , $specList );
		$this->display();
	}

	/**
	 * 当商品详情页点击 规格时 异步获取货品相关数据
	 */
	public function ajaxGetProduct ()
	{
		$gid       = I( 'post.gid' );
		$combine   = I( 'post.combine' );
		$goodsList = ( new GoodsListModel() )->where( "gid=$gid and combine='$combine'" )->find();
		if ( !$goodsList ) {//没有数据返回
			echo json_encode( [ 'status' => false , 'message' => '无货' ] , JSON_UNESCAPED_UNICODE );
			die;
		}
		$specList    = ( new GoodsAttrModel() )->where( "gtid in (" . $combine . ")" )->select();
		$gtvalue_str = '';
		$added_total = 0;
		foreach ( $specList as $sl ) {
			$gtvalue_str .= $sl[ 'gtvalue' ] . '-';
			$added_total += $sl[ 'added' ];
		}

		$specList[ 'gtvalue_str' ] = rtrim( $gtvalue_str , '-' );
		$specList[ 'added_total' ] = $added_total;
		echo json_encode( [ 'status' => true , 'product' => $specList ,'goodsList'=>$goodsList] , JSON_UNESCAPED_UNICODE );
		die;
//		select * form goods_attr where gtid in (28,31);
	}
}